var menuId; 
var changefid;
var changeicon;
var rows;
function basePath(){
    //获取当前网址，如： http://localhost:8080/ems/Pages/Basic/Person.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： /ems/Pages/Basic/Person.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8080
    var localhostPath = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/ems
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    //获取项目的basePath   http://localhost:8080/ems/
    var basePath=localhostPath+projectName+"/";
    return basePath;
};

jQuery(document).ready(function() {
	var orgData = {};
	$.ajax({
		async : false,
		url : projectPath + "user/getCurrentUser.do",
		data : {},
		dataType : "json",
		success : function(data) {
			orgData = data;
		}
	});
	initTable();
	
//	bindOrg1('orgSelect');
//	bindOrg("orgSelect","2","0","");
	
//	bindItem("bespeakItems","","");
	
//	bindDict1("timeSelect","bespeak_period","");
	
	App.setPage("bespeakrule");  //Set current page
	App.init(); //Initialise plugins and elements
	
	//列表查询事件
	$('#search').click(function(){
		$('#bookingTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
	});
	
	//保存数据事件
	$('#save').click(function(){
		$("#ifModal")[0].contentWindow.save();
	});
	
	
	//新增规则
	$('#addRule').click(function(){
		setModalSize(0.6, 0.65);
		$('#ifModal').attr("src", "add.html");
		$('#orgSelect').val(orgData.orgname);
		$('#orgSelect').attr('data', orgData.orgcode);
		$('#title').html("新增预约规则");
		$("#modalMenu").modal('show');
	});
	
	//批量删除
	$('#batchDelete').click(function(){
		var data = $('#bookingTable').bootstrapTable('getSelections');
		if(data.length <= 0){
			window.wxc.xcConfirm('请勾选要<strong>批量删除</strong>的预约规则数据', window.wxc.xcConfirm.typeEnum.info);
			return;
		}
		var ruleIds = "";
		var names = "";
		for(var i = 0; i < data.length; i++){
			ruleIds += data[i].ruleid + ",";
		}
		
		ruleIds = ruleIds.substring(0, ruleIds.length - 1);
		window.wxc.xcConfirm('是否<strong>批量删除</strong>选中的预约规则数据?<br /><span style="color:red;"></span>', window.wxc.xcConfirm.typeEnum.confirm,{
			onOk:function(v){
				$.ajax({ 
					url: basePath() + 'rule/batchDelete.do',
					data: {"ruleIds": ruleIds},
					dataType: "json",
					success: function(data){	            						
						if(data.result == 1){        	
				        	window.wxc.xcConfirm('删除预约规则成功!', window.wxc.xcConfirm.typeEnum.success,{
								onOk:function(v){
									$('#bookingTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
								}
							});
						}
			      	}
				});
			}
		});
	});
	
	//保存数据事件
//	$('#save').click(function(){
//		var ruleData = $("#ruleForm").serializeObject();
//		var b=$("#bespeakItems").val();
//		ruleData.ITEMNAME=$("#bespeakItems").find("option[value="+b+"]").html();
//		ruleData.ORGCODE=$("#orgSelect").attr("data");
//		if (!check(ruleData))
//			return true;		
//		var ruleId=$("#ruleId").val();
//		if(ruleId==""){
//			$.ajax({ 
//				method: 'post',
//				url: basePath() + 'rule/insertRuless.do',
//				data: JSON.stringify(ruleData),
//				dataType: "json",
//		        contentType: "application/json",
//				success: function(data){	
//			    	window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.info);
//			    	if(data.result == 1){
//			    		$('#bookingTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
//			    		$('#modalMenu').modal('hide');
//			    	}
//		      	}
//			})
//		}else{
//			$.ajax({ 
//				method: 'post',
//				url: basePath() + 'rule/updateRule.do',
//				data: JSON.stringify(ruleData),
//				dataType: "json",
//		        contentType: "application/json",
//				success: function(data){	
//					window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.info);	
//			    	if(data.result == 1){
//			    		$('#bookingTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
//			    		$('#modalMenu').modal('hide');
//			    	}
//		      	}
//			})
//		}
//	});
	
	function check(data) {
		var result = true;
		var mustStr = "ORGCODE,ITEMID,RESERVENUM,RESERVETIME,ISPUSHLISH";
		var strMsg = "";
		var mustStrs = mustStr.split(',');
		for (var i = 0; i < mustStrs.length; i++) {
			var obj = $('[name="' + mustStrs[i] + '"]');
			var obj1 = obj.attr("placeholder");
			if (obj.val() == "") {
				strMsg += obj1.substring(0, 3)
						+ "<span style='color:red;'><strong>"
						+ obj1.substring(3, obj1.lengh) + "</strong></span>！<br />";
				result = false;
			}
		}
		if (strMsg != "") {
			window.wxc.xcConfirm(strMsg, window.wxc.xcConfirm.typeEnum.error);
		}
		return result;
	}
	
	
	//清空表单数据事件
	$("#modalMenu").on("hidden.bs.modal", function() {
//		$("#orgSelect option:first").prop("selected",true);
		$("#orgSelect").val("");
		$("#orgSelect").removeAttr("data");
		$("#bespeakItems option:first").prop("selected",true);
		$("#ruleId").val("");
		$("#reserveNum").val("");
		$("#timeSelect option:first").prop("selected",true);	
		$("[name='isPushlish'][value='0']").prop("checked", true);		
	});
	
	
	$("#modalMenu").on("shown.bs.modal", function() {

		$("#selectfid").find("option[value="+changefid+"]").attr("selected",true);
		
	});
});		

function initTable(){	
	$('#bookingTable').bootstrapTable({
		method: 'post',
	    url: basePath() + 'rule/list.do',
	    pagination: true, //分页
	    dataType: "json",
        contentType: "application/json",
        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        striped: true,      //是否显示行间隔色
        sidePagination: "server",
        ////查询参数,每次调用是会带上这个参数，可自定义                         
        queryParams:function(params) {
            return {
                	pageNum: params.offset / params.limit + 1,
                	pageSize: params.limit,
                	itemname:$("#itemName").val()
                };
        },
	    columns: [{
            field : 'checked',
            checkbox : true

        }, {  
            field : 'number',  
            title : '序号',  
            align : 'center',
            width : '80px',
            formatter : function(value, row, index) { 
// 		                return index + 1;  
                var page = $('#bookingTable').bootstrapTable("getPage");  
                return page.pageSize * (page.pageNumber - 1) + index + 1;  
            }  
        }, {
            field: 'orgcode',
            visible : false	
	    }, {
	        field: 'ruleid',
            visible : false	
	    }, {
	        field: 'itemid',
            visible : false	
	    }, {	    	
	        field: 'orgname',
	        title: '所属机构名称',
	    }, {
	        field: 'itemname',
	        title: '行政许可项目名称'
        },
//         {
//	        field: 'reservenum',
//	        title: '预约人数限制'
//	    }, {
//	        field: 'reservetime',
//	        title: '预约时间段'
//	    },
        {
	        field: 'ispushlish',
	        title: '是否开通预约功能',
	        formatter:function(value){
	        	if(value=="1"){
	        		return "是"
	        	}else{
	        		return "否"
	        	}
	        }
	    },{
            field: 'operate',
            title: '操作',
            align: 'center',
            width: '250px',
            events: operateEvents,
            formatter: operateFormatter
        } ]
	});
}

function operateFormatter(value, row, index) {
    return [
        '<button type="button" class="Edit btn btn-warning  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-edit"></span>编辑</button>',
        '<button type="button" class="Copy btn btn-primary  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-file"></span>复制</button>',
        '<button type="button" class="Delete btn btn-danger  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span>删除</button>'
    ].join('');
}

window.operateEvents = {
    'click .Edit': function (e, value, row, index) {
    	setModalSize(0.6, 0.65);
    	rows = row;
		$('#title').html("预约规则修改");
		$('#ifModal').attr("src", "add.html?ruleId="+row.ruleid);
		$("#modalMenu").modal('show');	
    },
    'click .Copy': function (e, value, row, index) {
    	setModalSize(0.6, 0.65);
    	rows = row;
		$('#title').html("新增预约规则");
		$('#ifModal').attr("src", "add.html?copy=1&ruleId="+row.ruleid);
		$("#modalMenu").modal('show');	
    },
    'click .Delete': function (e, value, row, index) {
    	
		var ruleId = row.ruleid;
		window.wxc.xcConfirm('是否<strong>删除</strong>选中的预约规则数据?<br /><span style="color:red;"></span>', window.wxc.xcConfirm.typeEnum.confirm, {
			onOk: function(v){
				$.ajax({ 
					url: basePath() + 'rule/deleteRule.do',
					data: {"ruleId": ruleId},
					dataType: "json",
					success: function(data){	            						
						if(data.result == 1){
	        	            window.wxc.xcConfirm('删除预约规则成功!', window.wxc.xcConfirm.typeEnum.success);
				        	$('#bookingTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
						}
			      	}
				});
			} 
		});
    }
 };



function setModalSize(widthPercent, heightPercent){
	var documentW = $(window).width();
	var documentH = $(window).height();
	$('#modalW').width(documentW * widthPercent);
	$('#modalH').height(documentH * heightPercent);
}
